/* eslint-disable */
import {
  zzsData,
  cwbbTransfrom,
  lrbTransFrom,
  xjllbTransFrom
} from "./data.js";
import { Ajax } from "../../lib/ajax.js";
import {
  nextTick,
  baoBiaoDetailBack,
  asyncFb3Detail,
  asyncFb1Detail,
  asyncFb2Detail,
  asyncFb4Detail,
  asyncJmsDetail,
  asyncZzsDetail,
  asyncCgmxbDetail,
  asyncFjsDetail,
  xgmflzlOption,
  xgmjmsOption,
  xgmssbOption,
  createNewTab,
  asyncXgmflzlDetail,
  asyncXgmjmsDetail,
  asyncXgmsbbDetail,
  qysdsA201010,
  qysdsA201010Table,
  qysdsA201020,
  qysdsA201020Table,
  qysdsA200000,
  qysdsA200000Table,
  qysdsA201030,
  qysdsA201030Table
} from "./asyncTableDetail.js";

import { asyncSetInterval, fixZeroInfo } from '../../lib/zeroReportUtils.js'


let pages = {
  pageIndex: ['/zjgfdzswj/main/home/wdxx/index.html', '/zjgfdzswj/main/home/wybs/index.html'],
  cwbbPage: ['/zjgfzjdzswjsbweb/pages/sb', 'xqycwbb'],
  zzsXgmPage: ['/zjgfzjdzswjsbweb/pages/sb', 'zzsxgmnsr'],
  zzsYbnsrPage: ['/zjgfctais2/wssb/ybnsr2012'],
  fjxPage: ['/zjgfzjdzswjsbweb/pages/sb', 'fjsf'],
  qysdsPage: ['/zjgfzjdzswjsbweb/pages/sb', 'jmczyjd'],
}

// 页面点击报税
const pagesCwbb = async (data) => {
  // 财务报表 - 增值税 - 附件税
  let timer = setInterval(async () => {
    let lis = Array.from(window.document.querySelectorAll("#wddblunbo > li"));
    if (lis) {
      clearInterval(timer);
      timer = null;
      let cwbbLi = lis.find(
        (li) =>
          li.innerText.includes("财务报表") && !li.innerText.includes("年度")
      );
      let zzsLi = lis.find((li) => li.innerText.includes("增值税"));
      let fjsLi = lis.find((li) =>
        li.innerText.includes("城建税、教育费附加、地方教育附加税"));
      let qysds = lis.find((li) => li.innerText.includes("居民企业所得税月"));
      if (cwbbLi && !cwbbLi.innerText.includes("已申报") && (typeof data.data.currentZeroInfo.cwbbInfo === 'object')) {
        let url = cwbbLi.querySelector("a").href;
        window.location.href = url;
      } else if (zzsLi && !zzsLi.innerText.includes("已申报")) {
        let url = zzsLi.querySelector("a").href;
        window.location.href = url;
      } else if (fjsLi && !fjsLi.innerText.includes("已申报")) {
        let url = fjsLi.querySelector("a").href;
        window.location.href = url;
      } else if (qysds && !qysds.innerText.includes("已申报")) {
        let url = qysds.querySelector('a').href;
        window.location.href = url;
      } else {
        // 申报完成
        let dbList = await getDbList();
        let backInfo = {
          ...data.data.currentZeroInfo,
          recordList: dbList
        };
        window.postMessage({
          event: 'zeroReportBack',
          data: backInfo
        }, '*');
      }
    }
  }, 500);
};

const getDbList = async () => {
  let href = "https://etax.zhejiang.chinatax.gov.cn/zjgfzjdzswjsbweb/nssb/nssb/dbrwinit.do";
  let postData = {
    xmzslx: 30
  };
  return new Promise((reslove, reject) => {
    Ajax.post({
      url: href,
      data: JSON.stringify(postData),
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json, text/javascript, */*; q=0.01"
      },
      success(res) {
        let data = JSON.parse(res);
        if (data.resultObj && data.resultObj.sbxmlist) {
          let dbList = data.resultObj.sbxmlist.map((item) => {
            let obj = {};
            let declareCycle = parseInt(item.sssq_z.split("-")[1])
              - parseInt(item.sssq_q.split("-")[1]);
            obj.declareName = item.sbxmmc;
            obj.accountBook = declareCycle === 11
              ? item.sssq_z.split("-")[0]
              : `${item.sssq_z.split("-")[0]}-${item.sssq_z.split("-")[1]}`;
            // obj.declareTime = item.sbrq;
            obj.sbxmdm = item.sbxmdm;
            obj.sssq_q = item.sssq_q;
            obj.sssq_z = item.sssq_z;
            obj.sbzt = item.sbzt;
            obj.sbzk = item.sbzk;
            // eslint-disable-next-line no-nested-ternary
            obj.declareCycle = declareCycle === 2
              ? "season"
              : declareCycle === 11
                ? "year"
                : "month";
            obj.isSuccess = parseInt(item.sbzk) === 1;
            return obj;
          });
          reslove(dbList);
        } else {
          reject(false);
        }
      }
    });
  });
};
window.addEventListener(
  "message",
  ({ data }) => {
    if (data.sender !== "content-script") {
      return false;
    }
    if (data.event === "baoBiaoDetailBack") {
      if (data.data.qsbNumber >= 3) {
        console.log("sbsb");
      } else {
        window.location.reload();
      }
    }
    // 零申报结束返回事件
    if (data.event === "zeroReportEnd") {
      setTimeout(() => {
        window.postMessage(
          {
            event: "asyncTableDetailRequest"
          },
          "*"
        );
      }, 100);
    }
    if (data.event === "asyncTableDetailRequestEnd") {
      window.postMessage(
        {
          event: "clearZeroReport"
        },
        "*"
      );
      setTimeout(() => {
        sessionStorage.gotologin = "Y";
        sessionStorage.removeItem("changeCompany");
        sessionStorage.removeItem("dsChangeCompany");
        // eslint-disable-next-line no-useless-concat
        window.location.href = "/" + "zjgfdzswj" + "/main/logout.jsp";
      }, 1000);
    }
  },
  false
);

// -------- 财务报表
const cwbbOption = async (data) => {
  let href = window.location.href;
  let dialogBox = document.querySelector(
    "#nssb_bszy > div > div.modal-footer > button"
  );
  if (dialogBox) dialogBox.click();
  // 资产负债表
  if (href.includes("/zjgfzjdzswjsbweb/pages/sb/nssb/bdlb.html")) {
    // 财务报表页面
    let timer = setInterval(() => {
      let zcfzb = document.querySelector("#sbbdlist > li:nth-child(1) > a");
      let llb = document.querySelector("#sbbdlist > li:nth-child(2) > a");
      let xjllb = document.querySelector("#sbbdlist > li:nth-child(3) > a");
      let qsb = document.querySelector("#sbbdlist > li:nth-child(5) > a");
      if (zcfzb && llb && xjllb && qsb) {
        clearInterval(timer);
        timer = null;
        if (!zcfzb.querySelector("img")) {
          createNewTab({ url: zcfzb.href });
        } else if (!llb.querySelector("img")) {
          createNewTab({ url: llb.href });
        } else if (!xjllb.querySelector("img")) {
          createNewTab({ url: xjllb.href });
        } else if (!qsb.querySelector("img")) {
          createNewTab({ url: qsb.href });
        } else {
          // 申报成功完成
          let recordList = data.currentZeroInfo.recordList;
          let cwbb = recordList.find(item => item.declareName.includes('财务报表'));
          cwbb.isSuccess = true;
          fixZeroInfo({recordList: [cwbb]});
          setTimeout(() => {
            window.location.href = "https://etax.zhejiang.chinatax.gov.cn/zjgfdzswj/main/home/wybs/index.html";  
          }, 1000);
        }
      }
    }, 200);
  } else if (
    href.includes(
      "/zjgfzjdzswjsbweb/pages/sb/cwbb/xqycwbb/sb_cwbb_xqy_zcfzb.html"
    )
  ) {
    zcfzbOption(data);
  } else if (
    href.includes(
      "/zjgfzjdzswjsbweb/pages/sb/cwbb/xqycwbb/sb_cwbb_xqy_lrb_yb.html"
    )
  ) {
    llbOption(data);
  } else if (
    href.includes(
      "/zjgfzjdzswjsbweb/pages/sb/cwbb/xqycwbb/sb_cwbb_xqy_xjllb_yb.html"
    )
  ) {
    xjllbOption(data);
  } else if (
    href.includes("/zjgfzjdzswjsbweb/pages/sb/cwbb/xqycwbb/qsb.html")
  ) {
    cwbbqsbOption(data);
  }
};

// 处理资产负债表
const zcfzbOption = async (data) => {
  let zcfzbData = data.currentZeroInfo.cwbbInfo.zcfzb;
  let transFromData = Object.keys(cwbbTransfrom);
  // 判断work是否有数据
  // 判断税局是否有数据
  let isinputData = false;
  let isWorkData = transFromData.find((item) => {
    let cell = zcfzbData[cwbbTransfrom[item]];
    let input = document.querySelector("#" + item);
    if (parseFloat(input.value)) isinputData = true;
    return parseFloat(cell.qmye) || parseFloat(cell.ncye);
  });
  if (isWorkData) { // 使用work数据
    transFromData.forEach((item) => {
      let input = document.querySelector("#" + item);
      let cell = zcfzbData[cwbbTransfrom[item]];
      // cell.qmye = 0;
      // cell.ncye = 0;
      let xnum = item.includes("qms") ? cell.qmye : cell.ncye;
      input.value = parseFloat(xnum);
      input.onblur();
    });
  } else if (!isWorkData) { // 使用固定数据
    let xx_030_qms = document.querySelector("#xx_030_qms").value;
    let xx_053_qms = document.querySelector("#xx_053_qms").value;
    if (!parseFloat(xx_030_qms) && !parseFloat(xx_053_qms)) {
      ['xx_009_qms', 'xx_051_qms'].forEach((item) => {
        let input = document.querySelector("#" + item);
        if (input) input.value = '0.01';
        input.onblur();
      });
    }
  }
  let submitBtn = document.querySelector(
    "body > form > div > table.table.table_footer > tbody > tr > td > a:nth-child(2)"
  );
  if (submitBtn.innerText.includes("提")) {
    submitBtn.click();
    let timers = setInterval(() => {
      let successBtn = document.querySelector(
        "body > div.zj-big-bg > div.zj-alert > div.zj-alert-body"
      );
      if (successBtn) {
        clearInterval(timers);
        timers = null;
        if (successBtn.innerText === "保存成功") {
          baoBiaoDetailBack("zcfzb", true);
        } else {
          window.postMessage({ event: "zeroReportFail" }, "*");
        }
      }
    }, 200);
  } else baoBiaoDetailBack("zcfzb", true);
};
// 处理利润表
const llbOption = async (data) => {
  let llbData = data.currentZeroInfo.cwbbInfo.lrb;
  let lrbKeys = Object.keys(lrbTransFrom);
  let isWorkData = lrbKeys.find((item) => {
    let cell = llbData[lrbTransFrom[item]];
    return parseFloat(cell.bqje) || parseFloat(cell.bnljje);
  });
  if (isWorkData) {
    lrbKeys.forEach((item) => {
      let input = document.querySelector("#" + item);
      let cell = llbData[lrbTransFrom[item]];
      let xnum = item.includes("sns") ? cell.bqje : cell.bnljje;
      xnum = parseFloat(xnum);
      if (xnum) {
        input.value = xnum;
        input.onblur();
      }
    });
  }
  let submitBtn = document.querySelector(
    "body > form > div > table.table.table_footer > tbody > tr > td > a:nth-child(2)"
  );
  if (submitBtn.innerText.includes("提")) {
    submitBtn.click();
    let timers = setInterval(() => {
      let successBtn = document.querySelector(
        "body > div.zj-big-bg > div.zj-alert > div.zj-alert-body"
      );
      if (successBtn) {
        clearInterval(timers);
        timers = null;
        if (successBtn.innerText === "保存成功") {
          baoBiaoDetailBack("lrb", true);
        } else {
          window.postMessage({ event: "zeroReportFail" }, "*");
        }
      }
    }, 200);
  } else {
    baoBiaoDetailBack("lrb", true);
  }
};
// 处理现金流量表
const xjllbOption = async (data) => {
  let xjllbData = data.currentZeroInfo.cwbbInfo.xjllb;
  let xjllbKeys = Object.keys(xjllbTransFrom);
  let isWorkData = xjllbKeys.find((item) => {
    let cell = xjllbData[xjllbTransFrom[item]];
    return parseFloat(cell.bqje) || parseFloat(cell.bnljje);
  });
  if (isWorkData) {
    xjllbKeys.forEach((item) => {
      let input = document.querySelector("#" + item);
      let cell = xjllbData[xjllbTransFrom[item]];
      let xnum = item.includes("sys") ? cell.bqje : cell.bnljje;
      xnum = parseFloat(xnum);
      if (xnum) {
        input.value = xnum;
        input.onblur();
      }
    });
  }
  let submitBtn = document.querySelector(
    "body > form > div > table.table.table_footer > tbody > tr > td > a:nth-child(2)"
  );
  if (submitBtn.innerText.includes("提")) {
    submitBtn.click();
    let timers = setInterval(() => {
      let successBtn = document.querySelector(
        "body > div.zj-big-bg > div.zj-alert > div.zj-alert-body"
      );
      if (successBtn) {
        clearInterval(timers);
        timers = null;
        if (successBtn.innerText === "保存成功") {
          baoBiaoDetailBack("lrb", true);
        } else {
          window.postMessage({ event: "zeroReportFail" }, "*");
        }
      }
    }, 200);
  } else {
    baoBiaoDetailBack("lrb", true);
  }
};
// 全申报
const cwbbqsbOption = async (data) => {
  let timers = setInterval(() => {
    let successBtn = document.querySelector(
      "body > div.zj-big-bg > div.zj-alert > div.zj-alert-body"
    );
    if (successBtn) {
      clearInterval(timers);
      timers = null;
      baoBiaoDetailBack("cwbbQsb", true);
    }
  }, 200);
};

// -----------------增值税

const zzsOption = async (data) => {
  let lis = Array.from(
    document.querySelectorAll("body > div.menu-div > div > ul > li > a")
  );
  let cgmxb = lis.find((item) => item.innerText.includes("存根联明细"));
  let fb1 = lis.find((item) => item.innerText.includes("附表一"));
  let fb2 = lis.find((item) => item.innerText.includes("附表二"));
  let fb3 = lis.find((item) => item.innerText.includes("附表三"));
  let fb4 = lis.find((item) => item.innerText.includes("附表四"));
  let jzmxb = lis.find((item) => item.innerText.includes("减免税明细表"));
  let zsssbb = lis.find((item) => item.innerText.includes("增值税申报表"));
  let qsb = lis.find((item) => item.innerText.includes("全申报"));
  let href = window.location.href;

  if (href.includes("zjgfctais2/wssb/ybnsr2012/zzs.jsp")) {
    if (!fb1.querySelector("img")) {
      // 附表1
      createNewTab({ url: fb1.href, isAutoClose: false });
    } else if (!fb2.querySelector("img")) {
      // 附表2
      fb2Option(data);
    } else if (!fb4.querySelector("img")) {
      // 附表4
      createNewTab({ url: fb4.href, isAutoClose: false });
    } else if (!jzmxb.querySelector("img")) {
      // 减免税明细表
      createNewTab({ url: jzmxb.href, isAutoClose: false });
    } else if (!zsssbb.querySelector("img")) {
      // 增值税明细表
      createNewTab({ url: zsssbb.href, isAutoClose: false });
    } else {
      // 存根 和 附表三
      if (!cgmxb.querySelector("img") && !qsb.querySelector("img")) {
        createNewTab({ url: cgmxb.href, isAutoClose: true });
      }
      if (!fb3.querySelector("img") && !qsb.querySelector("img")) {
        createNewTab({ url: fb3.href, isAutoClose: true });
      }
      if (!qsb.querySelector("img")) {
        setTimeout(() => {
          createNewTab({
            url:
              "https://etax.zhejiang.chinatax.gov.cn/zjgfctais2/wssb/ybnsr2012/sb_nssb_check_zzs.jsp?gdsjh=1&sfyctj=N",
            isAutoClose: true,
            isQsb: true
          });
        }, 3000);
      } else {
        // 申报完成 同步申报表
        let recordList = data.currentZeroInfo.recordList;
        let zzs = recordList.find(item => item.declareName.includes('增值税'));
        zzs.isSuccess = true;
        fixZeroInfo({recordList: [zzs]});
        await createNewTab({ url: fb1.href, isAutoClose: true }, true);
        await createNewTab({ url: fb2.href, isAutoClose: true }, true);
        await createNewTab({ url: fb4.href, isAutoClose: true }, true);
        await createNewTab({ url: jzmxb.href, isAutoClose: true }, true);
        await createNewTab({ url: zsssbb.href, isAutoClose: true }, true);
        if (cgmxb.querySelector("img")) {
          await createNewTab({ url: cgmxb.href, isAutoClose: true }, true);
        }
        if (fb3.querySelector("img")) {
          await createNewTab({ url: fb3.href, isAutoClose: true }, true);
        }
        window.location.href = "https://etax.zhejiang.chinatax.gov.cn/zjgfdzswj/main/home/wybs/index.html";
      }
    }
  }

  if (href.includes("sb_zzs_flzl1.jsp")) {
    fb1Option(data);
  }
  if (href.includes("dis_zzs_flzl1.jsp")) {
    asyncFb1Detail(data);
  }
  if (href.includes("dis_zzs_flzl2.jsp")) {
    asyncFb2Detail(data);
  }
  if (href.includes("sb_zzs_flzl4_2019.jsp")) {
    fb4Option(data);
  }
  if (href.includes("dis_zzs_flzl4_2019.jsp")) {
    asyncFb4Detail(data);
  }
  if (href.includes("sb_zzs_jms_sbmxb.jsp")) {
    jzmxbOption(data);
  }
  if (href.includes("dis_zzs_jms_sbmxb.jsp")) {
    asyncJmsDetail(data);
  }
  if (href.includes("sb_zzs_ybnsr1.jsp")) {
    zsssbbOption(data);
  }
  if (href.includes("dis_zzs_ybnsr.jsp")) {
    asyncZzsDetail(data);
  }
  if (
    href.includes("sb_zzs_flzl4.jsp")
    || href.includes("sb_zzs_flzl4_js.jsp")
  ) {
    cgmxbOption(data);
  }
  if (href.includes("dis_zzs_flzl4.jsp")) {
    asyncCgmxbDetail(data);
  }
  if (href.includes("sb_zzs_flzl3_2012.jsp")) {
    fb3Option(data);
  }
  if (href.includes("ybnsr2012/dis_zzs_flzl3_2012.jsp")) {
    asyncFb3Detail(data);
  }
};

const zzsXqyOption = async (data) => {
  let href = window.location.href;
  if (href.includes("zjgfzjdzswjsbweb/pages/sb/nssb/bdlb.html")) {
    setTimeout(async () => {
      let btn = document.querySelector(
        "#nssb_bszy > div > div.modal-footer > button"
      );
      if (btn) btn.click();
      let timer = setInterval(async () => {
        let lis = document.querySelectorAll("#sbbdlist > li > a");
        if (lis) {
          clearInterval(timer);
          timer = null;
          lis = Array.from(lis);
          let flzl = lis.find((item) => item.innerText.includes("附列资料"));
          let jmsmxb = lis.find((item) =>
            item.innerText.includes("减免税明细表"));
          // let fwsktcb = lis.find(item => item.innerText.includes('防伪税控调查表'));
          let sbb = lis.find((item) => item.innerText.includes("申报表"));
          let qsb = lis.find((item) => item.innerText.includes("全申报"));
          if (!flzl.querySelector("img")) {
            createNewTab({ url: flzl.href, isAutoClose: false });
          } else if (!jmsmxb.querySelector("img")) {
            createNewTab({ url: jmsmxb.href, isAutoClose: false });
          } else if (!sbb.querySelector("img")) {
            createNewTab({ url: sbb.href, isAutoClose: false });
          } else if (!qsb.querySelector("img")) {
            createNewTab({ url: qsb.href, isAutoClose: true });
            setTimeout(() => {
              window.location.reload();
            }, 3000);
          } else {
            // 申报完成 同步申报表
            let recordList = data.currentZeroInfo.recordList;
            let zzs = recordList.find(item => item.declareName.includes('增值税'));
            zzs.isSuccess = true;
            fixZeroInfo({recordList: [zzs]});
            await createNewTab({ url: flzl.href, isAutoClose: true }, true);
            await createNewTab({ url: jmsmxb.href, isAutoClose: true }, true);
            await createNewTab({ url: sbb.href, isAutoClose: true }, true);
            window.location.href = "https://etax.zhejiang.chinatax.gov.cn/zjgfdzswj/main/home/wybs/index.html";
          }
        }
      }, 500);
    }, 1000);
  }
  if (href.includes("xgmnsr/sb_zzs_xgmnsr_flzl.html")) {
    // 附录资料
    xgmflzlOption();
  }
  if (href.includes("xgmnsr/dis_zzs_xgmnsr_flzl.html")) {
    // 附录资料
    asyncXgmflzlDetail();
  }
  if (href.includes("xgmnsr/sb_zzs_jms_sbmxb.html")) {
    // 减增明细表
    xgmjmsOption();
  }
  if (href.includes("xgmnsr/dis_zzs_jms_sbmxb.html")) {
    // 减增明细表
    asyncXgmjmsDetail();
  }
  if (href.includes("xgmnsr/sb_zzs_xgmnsr.html")) {
    // 申报表
    xgmssbOption();
  }
  if (href.includes("xgmnsr/dis_zzs_xgmnsr.html")) {
    // 申报表
    asyncXgmsbbDetail();
  }
};

// 存根明细表
const cgmxbOption = (data) => {
  let submitBtn = document.querySelector(
    "body > form > table:nth-child(3) > tbody > tr:nth-child(3) > td > div > a:nth-child(1)"
  );
  if (submitBtn && submitBtn.innerText.includes("发票数据下载")) {
    submitBtn.click();
  }
  let submitBtn1 = document.querySelector("body > form > div > a:nth-child(3)");
  if (submitBtn1 && submitBtn1.innerText.includes("确认提交")) {
    submitBtn1.click();
  }
};
// 附表3
const fb3Option = (data) => {
  let submitBtn = document.querySelector(
    "body > div.bottom_btn_div > a:nth-child(2)"
  );
  if (submitBtn.innerText.includes("提")) {
    submitBtn.click();
  }
};
// 附表1
const fb1Option = (data) => {
  let submitBtn = document.querySelector("body > form > div > a:nth-child(2)");
  if (submitBtn && submitBtn.innerText.includes("提")) {
    submitBtn.click();
    baoBiaoDetailBack("zzsFb1", true, 1000);
  }
};
// 附表2
const fb2Option = async (data) => {
  let fb2 = await zzsFB("fb2");
  if (fb2) window.location.reload();
};
// 附表4
const fb4Option = async (data) => {
  let submitBtn = document.querySelector("body > form > div > a:nth-child(2)");
  if (submitBtn.innerText.includes("提")) {
    submitBtn.click();
    baoBiaoDetailBack("zzsFb4", true, 1000);
  }
};
// 减免税明细表
const jzmxbOption = async (data) => {
  let submitBtn = document.querySelector(
    "body > div.bottom_btn_div > a:nth-child(2)"
  );
  if (submitBtn.innerText.includes("提")) {
    submitBtn.click();
    baoBiaoDetailBack("zzsJzmxb", true, 1000);
  }
};
// 增值税申报表
const zsssbbOption = async (data) => {
  let submitBtn = document.querySelector(
    "body > div.bottom_btn_div > a:nth-child(2)"
  );
  if (submitBtn.innerText.includes("提")) {
    submitBtn.click();
    baoBiaoDetailBack("zsssbbOption", true, 1000);
  }
};

const zzsFB = async (type, hydm = "") => {
  return new Promise((resole, reject) => {
    const { url, postData } = zzsData[type];
    let headers = {
      Accept:
        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
      "Content-Type": "application/x-www-form-urlencoded"
    };
    postData.kssj = new Date().getTime();
    if (hydm) postData.hydm = hydm;
    let keys = Object.keys(postData);
    let postDataArr = keys.map(
      (key) => `${encodeURIComponent(key)}=${encodeURIComponent(postData[key])}`
    );
    Ajax.post({
      url: url,
      data: postDataArr.join("&"),
      headers,
      success(res) {
        resole(true);
      }
    });
  });
};

const fjsfOption = async (data) => {
  let href = window.location.href;
  if (href.includes("zjgfzjdzswjsbweb/pages/sb/nssb/bdlb.html")) {
    let dialogBox = document.querySelector(
      "#nssb_bszy > div > div.modal-footer > button"
    );
    if (dialogBox) dialogBox.click;
    let timer = setInterval(async () => {
      let sbb = document.querySelector("#sbbdlist > li:nth-child(1) > a");
      let qsb = document.querySelector("#sbbdlist > li:nth-child(2) > a");
      if (sbb) {
        clearInterval(timer);
        timer = null;
        if (!sbb.querySelector("img")) {
          createNewTab({ url: sbb.href, isAutoClose: false });
        } else if (!qsb.querySelector("img")) {
          createNewTab({ url: qsb.href, isAutoClose: true, isQsb: true });
          setTimeout(() => {
            window.location.reload();
          }, 2000);
        } else {
          let recordList = data.currentZeroInfo.recordList;
          let fjs = recordList.find(item => item.declareName.includes('城建税、教育费附加、地方教育附加税'));
          fjs.isSuccess = true;
          fixZeroInfo({recordList: [fjs]});
          // 同步申报明细
          await createNewTab({ url: sbb.href, isAutoClose: true }, true);
          window.location.href = "https://etax.zhejiang.chinatax.gov.cn/zjgfdzswj/main/home/wybs/index.html";
        }
      }
    }, 200);
  }

  if (
    href.includes("/zjgfzjdzswjsbweb/pages/sb/dsbb/fjssbb/sb_fjsf_cjjyfj.html")
  ) {
    fjssqbOption();
  }
  if (
    href.includes("zjgfzjdzswjsbweb/pages/sb/dsbb/fjssbb/dis_fjsf_cjjyfj.html")
  ) {
    asyncFjsDetail();
  }
};

const fjssqbOption = () => {
  let submitBtn = document.querySelector("#tj");
  if (submitBtn && submitBtn.innerText.includes("提")) {
    submitBtn.click();
    baoBiaoDetailBack("fjsqsbOption", true, 1000);
  }
};

const zeroQysds = async (data) => {
  let href = window.location.href;
  if (href.includes('zjgfzjdzswjsbweb/pages/sb/nssb/bdlb.html')) {
    let timer = setInterval(async()=> {
      let lis = document.querySelectorAll("#sbbdlist > li > a");
      if(lis.length) {
        clearInterval(timer);
        timer = null;
        let A201010 = Array.from(lis).find(item => item.innerText.includes('A201010'));
        let A201020 = Array.from(lis).find(item => item.innerText.includes('A201020'));
        let A200000 = Array.from(lis).find(item => item.innerText.includes('A200000'));
        let A201030 = Array.from(lis).find(item => item.innerText.includes('A201030'));
        let qsb = Array.from(lis).find(item => item.innerText.includes('全申报'));
        if(!A201010.querySelector('img')) {
          createNewTab({ url: A201010.href, isAutoClose: false });
        } else if(!A201020.querySelector('img')) {
          createNewTab({ url: A201020.href, isAutoClose: false });
        } else if(!A200000.querySelector('img')) {
          createNewTab({ url: A200000.href, isAutoClose: false });
        } else if(!A201030.querySelector('img')) {
          createNewTab({ url: A201030.href, isAutoClose: false });
        } else if(!qsb.querySelector('img')) {
          createNewTab({ url: qsb.href, isAutoClose: true, isQsb: true });
        } else {
          let recordList = data.currentZeroInfo.recordList;
          let qysds = recordList.find(item => item.declareName.includes('居民企业所得税月'));
          qysds.isSuccess = true;
          fixZeroInfo({recordList: [qysds]});
          // 同步申报表
          await createNewTab({ url: A201010.href, isAutoClose: false }, true);
          await createNewTab({ url: A201020.href, isAutoClose: false }, true);
          await createNewTab({ url: A200000.href, isAutoClose: false }, true);
          await createNewTab({ url: A201030.href, isAutoClose: false }, true);
          window.location.href = "https://etax.zhejiang.chinatax.gov.cn/zjgfdzswj/main/home/wybs/index.html";
        }
        return true;
      }
    }, 200)

  }

  if (href.includes('/jmczyjd2020/sb_jdsds_A201010.html')) {
    qysdsA201010();
  }
  if (href.includes('jmczyjd2020/dis_jdsds_A201010.html')) {
    qysdsA201010Table();
  }
  
  if (href.includes('/jmczyjd2020/sb_jdsds_A201020.html')) {
    qysdsA201020();
  }
  if (href.includes('/jmczyjd2020/dis_jdsds_A201020.html')) {
    qysdsA201020Table();
  }
  if (href.includes('/jmczyjd2020/sb_jdsds_A200000.html')) {
    qysdsA200000(data);
  }
  if (href.includes('/jmczyjd2020/dis_jdsds_A200000.html')) {
    qysdsA200000Table(data);
  }
  if (href.includes('jmczyjd2020/sb_jdsds_A201030.html')) {
    qysdsA201030(data);
  }
  if (href.includes('/jmczyjd2020/dis_jdsds_A201030.html')) {
    qysdsA201030Table(data);
  }
  
};

let handlePageIndex = async (data) => {
  let {recordList} = data;
  await asyncSetInterval(async () => {
    let lis = Array.from(window.document.querySelectorAll("#wddblunbo > li"));
    if (lis) {
      let dbList = await getDbList();
      if (recordList.length < dbList.length) {
        fixZeroInfo({recordList: dbList});
        setTimeout(() => {
          window.location.reload();
        }, 1000);
      } else {
        // 财务报表
        let cwbb = recordList.find(item => item.declareName.includes('财务报表'));
        if (cwbb && !cwbb.isSuccess) {
          let cwbbLi = lis.find((li) =>li.innerText.includes(cwbb.declareName) && !li.innerText.includes("年度"));
          let url = cwbbLi.querySelector("a").href;
          window.location.href = url; 
          return true;
        }
        // 增值税 - 小规模 and 一般
        let zzs = recordList.find(item => item.declareName.includes('增值税'));
        if (zzs && !zzs.isSuccess) {
          let zzsLi = lis.find((li) => li.innerText.includes(zzs.declareName));
          window.location.href = zzsLi.querySelector("a").href;
          return true;
        }
        // 附加税
        let fjs = recordList.find(item => item.declareName.includes('城建税、教育费附加、地方教育附加税'));
        if (fjs && !fjs.isSuccess) {
          let fjsLi = lis.find((li) => li.innerText.includes(fjs.declareName));
          window.location.href = fjsLi.querySelector("a").href;
          return true;
        }
        // 企业所得税
        let qysds = recordList.find(item => item.declareName.includes('居民企业所得税月'));
        if (qysds && !qysds.isSuccess) {
          let qysdsLi = lis.find((li) => li.innerText.includes(qysds.declareName));
          window.location.href = qysdsLi.querySelector("a").href;
          return true;
        }
        
        setTimeout(() => {
          window.postMessage({
            event: 'zeroReportBack',
            data: {...data}
          }, '*');
        }, 1000);
      }
      return true;
    }
  })
}

const isPage = (page, isEvery = true) => {
  let href = window.location.href;
  if(isEvery) return pages[page].every(item => href.includes(item));
  return pages[page].find(item => href.includes(item));
};

const zeroReportStart = async (data) => {
  console.log(data);
  let href = window.location.href;
  if( isPage('pageIndex', false)) { // 主要操作同步报表
    handlePageIndex(data.currentZeroInfo);
  }
  if( isPage('cwbbPage')) { // 财务报表
    cwbbOption(data)
  }
  if (isPage('zzsXgmPage')) {
    zzsXqyOption(data);
  }
  if (isPage('zzsYbnsrPage')) {
    zzsOption(data);
  }
  if (isPage('fjxPage')) {
    fjsfOption(data);
  }
  if (isPage('qysdsPage')) {
    zeroQysds(data);
  }
}
export {
  pagesCwbb, cwbbOption, zzsOption, fjsfOption, zzsXqyOption, zeroQysds, zeroReportStart
};
